package com.gopay.checkorder.service.task;

import com.gopay.checkorder.dao.BisTimingFuseDao;
import com.gopay.checkorder.service.sentinel.BcdlOrderSentinel;
import com.gopay.common.domain.bank.bcdl.BisTimingFuse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class TimeFuseTaskImpl implements Task {

	private final static Logger logger = LoggerFactory.getLogger(TimeFuseTaskImpl.class);

	@Resource(name = "bisTimingFuseDao")
	private BisTimingFuseDao bisTimingFuseDao;

	@Autowired
	private Map<String,BcdlOrderSentinel> allBank;

	/**
	 * 定时熔断定时任务执行
	 */
	public void doTask() {
		logger.info("-------------定时熔断定时任务开始------------------------------");
		List<BisTimingFuse> list = bisTimingFuseDao.findBisTimingFuseAll();//查询出所有已执行或未知行的定时熔断
        Date current=new Date();
        logger.info("----------------current："+current+"-----------------------");
        for(BisTimingFuse bisTimingFuse:list){
			BcdlOrderSentinel bcdlOrderSentinel = allBank.get(bisTimingFuse.getSentinelCode());
			if(bisTimingFuse.getTimingStatus().equals(BisTimingFuse.TimingStatus.EXECUTING.getCode())){//筛出执行中的
				//当前时间current在目前执行中不在熔断时间中或当前时间等于结束时间，则进行熔断结束操作
				if((current.after(bisTimingFuse.getStartFusingTs()) && current.after(bisTimingFuse.getEndFusingTs()))||current.compareTo(bisTimingFuse.getEndFusingTs())==0){
					if(bcdlOrderSentinel!=null) {
						bcdlOrderSentinel.restartForTime(bisTimingFuse.getSq());
						logger.info("------熔断解除-------定时熔断sq="+bisTimingFuse.getSq()+"任务结束--------SentinelCode="+bisTimingFuse.getSentinelCode()+"----------------------");
					}
				}
			}else if(bisTimingFuse.getTimingStatus().equals(BisTimingFuse.TimingStatus.UNEXECUTED.getCode())) {//筛出未执行的
				//当前时间current在目前未执行熔断时间中或当前时间等于开始时间，则进行熔断执行操作
				if ((current.after(bisTimingFuse.getStartFusingTs()) && current.before(bisTimingFuse.getEndFusingTs()))||current.compareTo(bisTimingFuse.getStartFusingTs())==0) {
					if(bcdlOrderSentinel!=null){
						bcdlOrderSentinel.stopForTime(bisTimingFuse.getSq());
						logger.info("-----熔断执行--------定时熔断sq="+bisTimingFuse.getSq()+"任务开始-------SentinelCode="+bisTimingFuse.getSentinelCode()+"-----------------------");
					}
				}
			}
		}
		logger.info("-------------定时熔断定时任务结束------------------------------");
	}
}
